package com.bestom.multispectrallight.callback;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothServerSocket;
import android.util.Log;

import com.bestom.multispectrallight.MainActivity;
import com.bestom.multispectrallight.ThisApplication;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static com.bestom.multispectrallight.callback.ScanCallback.mArrayList;

/**
 * @author shulman
 */
public class BTGattCallback extends BluetoothGattCallback {

    private final String TAG = "BTGattCallback";
    private UUID notifyService;
    private UUID notifyChara;
    private UUID writeService;
    private UUID writeChara;
    private BluetoothGattCharacteristic writeCharacteristic;
    private BleListen mBleListen;
    private BTGattCallback(BleListen bleListen) {
        mBleListen = bleListen;
    }

    public static BTGattCallback getInstance(BleListen bleListen) {
        /*if (_instance == null)*/
        BTGattCallback _instance = new BTGattCallback(bleListen);
        return _instance;
    }

    /**
     * 断开或连接 状态发生变化时调用
     */
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTED:
                //发现服务
                gatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                Log.i("disconnect","蓝牙断开");
                mBleListen.disConnect(gatt);
                break;
            case BluetoothProfile.STATE_CONNECTING:
            case BluetoothProfile.STATE_DISCONNECTING:
            default:break;
        }
    }

    /**
     * 发现设备（真正建立连接）
     */
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);

        //直到这里才是真正建立了可通信的连接
        initServiceAndChara();
        //订阅通知
        if (notifyService != null && notifyChara != null) {
            BluetoothGattCharacteristic characteristic = mBluetoothGatt
                    .getService(notifyService).getCharacteristic(notifyChara);
            boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
            if (isEnableNotification) {
                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                if (descriptorList != null && descriptorList.size() > 0) {
                    for (BluetoothGattDescriptor descriptor : descriptorList) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        mBluetoothGatt.writeDescriptor(descriptor);
                    }
                }
            }
        }
        mBleListen.connect(mBluetoothGatt, writeCharacteristic);
    }

    /**
     * 读操作的回调
     */
    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);
        Log.d(TAG, "onCharacteristicRead()  status=" + status);
    }

    /**
     * 写操作的回调
     */
    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);
        Log.i(TAG, "Receive data--->" + Arrays.toString(characteristic.getValue()));
    }

    /**
     * 接收到硬件返回的数据
     */
    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);
    }

    private BluetoothGatt mBluetoothGatt;

    /**设备gatt集合
     * *
     */

    private boolean isFirst;
    private void initServiceAndChara(){
        mBluetoothGatt = ThisApplication.getApplication().getBluetoothGatt();
        isFirst = true;
        try {
            List<BluetoothGattService> bluetoothGattServices= mBluetoothGatt.getServices();
            for (BluetoothGattService bluetoothGattService:bluetoothGattServices){
                List<BluetoothGattCharacteristic> characteristics=bluetoothGattService.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic:characteristics){
                    int charaProp = characteristic.getProperties();
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                        UUID readChara = characteristic.getUuid();
                        UUID readService = bluetoothGattService.getUuid();
                        //Log.i(TAG,"read_chara="+ readChara +"----read_service="+ readService);
                    }
                    //服务和特征值
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0 && isFirst) {
                        isFirst = false;
                        writeChara =characteristic.getUuid();
                        writeService =bluetoothGattService.getUuid();
                        writeCharacteristic = mBluetoothGatt.getService(writeService).getCharacteristic(writeChara);
                        //Log.i(TAG,"write_chara="+ writeChara +"----write_service="+ writeService);
                    }
                    UUID writeNoResponseService;
                    UUID writeNoResponseChara;
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                        writeNoResponseChara =characteristic.getUuid();
                        writeNoResponseService =bluetoothGattService.getUuid();
                        //Log.i(TAG,"writeNoResponseChara="+ writeNoResponseChara +"----writeNoResponseService="+ writeNoResponseService);
                    }

                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                        notifyChara =characteristic.getUuid();
                        notifyService =bluetoothGattService.getUuid();
                        //Log.i(TAG,"notify_chara="+ notifyChara +"----notify_service="+ notifyService);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                        UUID indicateChara = characteristic.getUuid();
                        UUID indicateService = bluetoothGattService.getUuid();
                        //Log.i(TAG,"indicate_chara="+ indicateChara +"----indicate_service="+ indicateService);
                    }
                }
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }


    public void write(BluetoothGatt mBluetoothGatt,BluetoothGattCharacteristic characteristic,byte[] bytes){
        if (characteristic == null) return;
        characteristic.setValue(bytes);
        mBluetoothGatt.writeCharacteristic(characteristic);
    }
    public void writeString(String info){
        if (writeCharacteristic == null) return;
        writeCharacteristic.setValue(info);
        mBluetoothGatt.writeCharacteristic(writeCharacteristic);
    }

    public void writeTo(byte[] bytes){
        BluetoothGattCharacteristic characteristic = mBluetoothGatt.getService(UUID.fromString("0000ff00-0000-1000-8000-00805f9b34fb")).getCharacteristic(UUID.fromString("0000ff02-0000-1000-8000-00805f9b34fb"));
        characteristic.setValue(bytes);
        mBluetoothGatt.writeCharacteristic(characteristic);
    }
}

